<?php
declare (strict_types=1);

namespace addons\V2\admin\model;

use app\common\model\Base;

class SpecItem extends Base
{
    protected $name = 'addons_mall_spec_item';

    public function spec()
    {
        return $this->hasOne(Spec::class, 'id', 'spec_id');
    }


    public static function setSpec($id, $value, $item_id = [])
    {
        try {
            $item = explode(',', $value);
            if ($item_id) {
                foreach ($item_id as $k => $v) {
                    $info = parent::where('id', $v)->find();

                    if ($info) {
                        if ($info['name'] != $item[$k]) {
                            $info['name'] = $item[$k];
                            $info->save();
                        }
                    }
                }
            }
            $spec_item = parent::where('spec_id', $id)->select();
            foreach ($spec_item as $val) {
                if (in_array($val['name'], $item)) {
                    $key = array_search($val['name'], $item);
                    unset($item[$key]);
                } else {
                    parent::destroy(['id' => $val['id']]);
                }
            }
            if ($item) {
                $all = [];
                foreach ($item as $v) {
                    $all[] = [
                        'spec_id' => $id,
                        'name' => $v
                    ];
                }
                (new self())->insertAll($all);
            }
            return true;
        } catch (\Exception $e) {
            return false;
        }
    }

    public static function getSpecItemName($str)
    {
        $spec_item = explode('-', $str);
        $arr = [];
        foreach ($spec_item as $v) {
            $arr[] = parent::where('id', $v)->value('name');
        }
        return implode('-', $arr);
    }


}
